package com.example.iread.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.iread.R;
import com.example.iread.activity.BookInfoActivity;
import com.example.iread.activity.BookListActivity;
import com.example.iread.activity.SearchActivity;
import com.example.iread.application.MyApplication;
import com.example.iread.bean.BookBean;
import com.example.iread.bean.TypeBean;
import com.example.iread.bean.UserBean;
import com.example.iread.dao.UserDao;
import com.example.iread.exception.MyException;
import com.example.iread.http.BookApi;
import com.example.iread.http.CategoryApi;
import com.example.iread.util.DensityUtil;
import com.example.iread.util.GsonUtil;
import com.example.iread.util.HttpUtil;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.android.material.shape.ShapeAppearanceModel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class HomeFragment extends Fragment {

    int[] doingsItem = {R.mipmap.image_doings_1, R.mipmap.image_doings_2, R.mipmap.image_doings_3};

    private View view;

    private Handler updateViewHandler;

    private final int UPDATE_VIEW_GAME = 0;
    private final int UPDATE_VIEW_SUGGESTION = 1;
    private final int UPDATE_VIEW_CATEGORIES_ICON = 2;
    private final String TAG = "SoRiya";
    private UserBean userBean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_home, container, false);

        Log.i(TAG, "onCreateView: Home");

        ImageButton btn_search = view.findViewById(R.id.btn_search);
        btn_search.setOnClickListener(v -> {
            Intent intent = new Intent(view.getContext(), SearchActivity.class);
            startActivity(intent);
        });

        updateViewHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
            }
        };

        UserDao userDao = MyApplication.getInstance().getDb().userDao();
        userBean = userDao.getOne();

        initGameList();
        initSuggestion();
        initCategoryList();

        return view;
    }

    private void initGameList() {
        TextView tv_user_name = view.findViewById(R.id.tv_user_name);
        tv_user_name.setText(userBean.nickname);
        // 设置首页活动列表
        ViewGroup doings_list = view.findViewById(R.id.doings_list);
        for (int item : doingsItem) {
            ShapeableImageView doings_item = new ShapeableImageView(view.getContext());
            ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(
                    DensityUtil.dpToPx(view.getContext(), 260), // 设置宽度
                    ViewGroup.LayoutParams.MATCH_PARENT
            );
            layoutParams.setMarginEnd(DensityUtil.dpToPx(view.getContext(), 16));
            doings_item.setLayoutParams(layoutParams);
            doings_item.setScaleType(ImageView.ScaleType.FIT_XY);
            doings_item.setImageResource(item);
            doings_item.setShapeAppearanceModel(
                    ShapeAppearanceModel.builder().build()
                            .withCornerSize(DensityUtil.dpToPx(view.getContext(), 10)) // 设置圆角
            );
            doings_list.addView(doings_item);
        }
    }

    private void initSuggestion() {
        int[] recBookItem = {R.mipmap.image_cover_1, R.mipmap.image_cover_2, R.mipmap.image_cover_3};
        // 设置首页推荐图书列表

        ViewGroup rec_book_list = view.findViewById(R.id.rec_book_list);

        int year = 7;

        String myBirth = userBean.birthday;

        if (myBirth != null) {
            String[] birthday = myBirth.split("-");

            String[] now = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()).split("-");

            year = Integer.parseInt(now[0]) - Integer.parseInt(birthday[0]);
            int month = Integer.parseInt(now[1]) - Integer.parseInt(birthday[1]);
            int day = Integer.parseInt(now[2]) - Integer.parseInt(birthday[2]);

            if (month > 0) {
                year++;
            } else if (month == 0) {
                if (day > 0) {
                    year++;
                }
            } else {
                year = 0;
            }
        }

        BookApi.getSuggestionList(year, res -> {
            Type type = TypeToken.getParameterized(List.class, BookBean.class).getType();
            List<BookBean> bookBeanList = GsonUtil.parseObject(res.data, type);
            if (bookBeanList == null) return;
            Log.i(TAG, "initSuggestion: " + bookBeanList);
            for (BookBean item : bookBeanList) {
                ShapeableImageView rec_book_item = new ShapeableImageView(view.getContext());
                ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(
                        DensityUtil.dpToPx(view.getContext(), 120), // 设置宽度
                        ViewGroup.LayoutParams.MATCH_PARENT
                );
                layoutParams.setMarginEnd(DensityUtil.dpToPx(view.getContext(), 16));
                rec_book_item.setLayoutParams(layoutParams);
                rec_book_item.setScaleType(ImageView.ScaleType.FIT_XY);
                rec_book_item.setOnClickListener(v -> {
                    Intent intent = new Intent(this.getContext(), BookInfoActivity.class);
                    intent.putExtra("bookId", item.id);
                    startActivity(intent);
                });

                Handler handler = new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        if (msg.what == UPDATE_VIEW_CATEGORIES_ICON) {
                            Bitmap bitmap = (Bitmap) msg.obj;
                            rec_book_item.setImageBitmap(bitmap);
                        }
                    }
                };

                new Thread(() -> {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(
                                new URL(HttpUtil.getImageUrl(item.cover)).openStream()
                        );
                        Message message = new Message();
                        message.what = UPDATE_VIEW_CATEGORIES_ICON;
                        message.obj = bitmap;
                        handler.sendMessage(message);
                    } catch (Exception e) {
                        throw new MyException(500, e.getMessage());
                    }
                }).start();
                rec_book_item.setShapeAppearanceModel(
                        ShapeAppearanceModel.builder().build()
                                .withCornerSize(DensityUtil.dpToPx(view.getContext(), 10)) // 设置圆角
                );
                handler.post(() ->  rec_book_list.addView(rec_book_item));
            }
        });
    }

    private void initCategoryList() {
        ViewGroup category_list = view.findViewById(R.id.category_list);
        CategoryApi.list(res -> {
            List<TypeBean> typeBeanList = new Gson().newBuilder().serializeNulls().create().fromJson(new Gson().toJson(res.data), TypeToken.getParameterized(List.class, TypeBean.class).getType());
            if (typeBeanList == null) return;
            for (TypeBean typeBean : typeBeanList) {
                // 最外层Layout
                LinearLayout typeLayout = new LinearLayout(view.getContext());
                ViewGroup.MarginLayoutParams marginLayoutParams = new LinearLayout.MarginLayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        DensityUtil.dpToPx(view.getContext(), 120)
                );
                marginLayoutParams.setMargins(0, 0, 0, DensityUtil.dpToPx(view.getContext(), 16));
                typeLayout.setLayoutParams(marginLayoutParams);
                typeLayout.setOrientation(LinearLayout.HORIZONTAL);
                typeLayout.setBackgroundResource(R.drawable.sh_booktype_1);

                // 图标Layout
                LinearLayout iconLayout = new LinearLayout(view.getContext());
                iconLayout.setLayoutParams(new LinearLayout.LayoutParams(
                        DensityUtil.dpToPx(view.getContext(), 120),
                        DensityUtil.dpToPx(view.getContext(), 120)
                ));
                iconLayout.setGravity(Gravity.CENTER);
                ImageView icon = new ImageView(view.getContext());
                icon.setLayoutParams(new LinearLayout.LayoutParams(
                        DensityUtil.dpToPx(view.getContext(), 80),
                        DensityUtil.dpToPx(view.getContext(), 80)
                ));

                Handler handler = new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        if (msg.what == UPDATE_VIEW_CATEGORIES_ICON) {
                            Bitmap bitmap = (Bitmap) msg.obj;
                            icon.setImageBitmap(bitmap);
                        }
                    }
                };

                new Thread(() -> {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(
                                new URL(HttpUtil.getImageUrl(typeBean.typeIcon)).openStream()
                        );
                        Message message = new Message();
                        message.what = UPDATE_VIEW_CATEGORIES_ICON;
                        message.obj = bitmap;
                        handler.sendMessage(message);
                    } catch (Exception e) {
                        throw new MyException(500, e.getMessage());
                    }
                }).start();
                iconLayout.addView(icon);

                // 内容Layout
                LinearLayout contentLayout = new LinearLayout(view.getContext());
                contentLayout.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1));
                contentLayout.setPadding(DensityUtil.dpToPx(view.getContext(), 10), 0, DensityUtil.dpToPx(view.getContext(), 10), 10);
                contentLayout.setOrientation(LinearLayout.VERTICAL);
                contentLayout.setGravity(Gravity.START | Gravity.CENTER);

                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                );
                TextView typeTitle = new TextView(view.getContext());
                typeTitle.setLayoutParams(layoutParams);
                typeTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
                typeTitle.setTextColor(Color.parseColor(typeBean.textColor));
                typeTitle.getPaint().setFakeBoldText(true);
                typeTitle.setPadding(0, DensityUtil.dpToPx(view.getContext(), 5), 0, DensityUtil.dpToPx(view.getContext(), 5));
                typeTitle.setText(typeBean.typeName);
                contentLayout.addView(typeTitle);

//                TextView typeDesc = new TextView(view.getContext());
//                typeDesc.setLayoutParams(layoutParams);
//                typeDesc.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
//                typeDesc.setTextColor(Color.parseColor("#FFCECECE"));
//                typeDesc.setText(typeBean.typeDesc);
//                contentLayout.addView(typeDesc);

                typeLayout.addView(iconLayout);
                typeLayout.addView(contentLayout);

                typeLayout.setOnClickListener(v -> {
                    Intent intent = new Intent(view.getContext(), BookListActivity.class);
                    intent.putExtra("typeId", typeBean.id);
                    startActivity(intent);
                });

                handler.post(() -> category_list.addView(typeLayout));
            }
        });
    }
}